package org.kfish.framework.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;

import org.kfish.framework.log.Log;
import org.kfish.framework.log.Log.LogType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class StreamUtil {

	private static final Logger LOGGER = LoggerFactory.getLogger(StreamUtil.class);
	
	public static String getString(InputStream is){
		return getString(is,"utf-8");
	}
	
	public static String getString(InputStream is,String CharsetName){
		StringBuilder sb = new StringBuilder();
		BufferedReader reader;
		String line;
		try {
			reader = new BufferedReader(new InputStreamReader(is,CharsetName));
			while((line = reader.readLine())!=null){
				sb.append(line);
			}
		} catch (IOException e) {
			LOGGER.error("get string failure",e);
			throw new RuntimeException(e);
		}
		return sb.toString();
		
	}
	
	public static void copyStream(InputStream in,OutputStream out){
		int len;
		byte[] buffer = new byte[4*1024];
		try {
			while((len=in.read(buffer, 0, buffer.length))!=-1){
				out.write(buffer, 0, len);
			}
			out.flush();
		} catch (IOException e) {
			Log.getLogger(LogType.DETAIL).error("copy stream failure",e);
			throw new  RuntimeException(e);
		}finally{
			try {
				in.close();
				out.close();
			} catch (IOException e) {
				Log.getLogger(LogType.DETAIL).error("close stream error",e);
			}
		}
		
	}
}
